package com.qf.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.qf.Resp.BaseResp;
import com.qf.borrower.Borrower;
import com.qf.classes.Clsses;
import com.qf.client.ClassesClient;
import com.qf.dao.UserRespository;
import com.qf.service.UserService;
import com.qf.user.TbUser;
import com.qf.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author H
 * @create 2020-11-03 11:11
 * @strive To be whoever you want to be.
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserRespository userRespository;

    @Autowired
    JWTUtils jwtUtils;

    @Autowired
    ClassesClient classesClient;

    @Override
    public BaseResp login(Borrower borrower) {
        String username = borrower.getUsername();
        String password = borrower.getPassword();
        //声明返回BaseResp
        BaseResp baseResp = new BaseResp();
        if (username == null || username.equals("") || password == null || password.equals("")) {
            baseResp.setCode(100001l);
            baseResp.setMessage("信息输入不完整");
            return baseResp;
        }

        Borrower byLoginNameAndPassword = userRespository.findByUsernameAndPassword(username, password);

        if (byLoginNameAndPassword == null) {
            baseResp.setCode(100002l);
            baseResp.setMessage("用户信息输入错误，请重新输入");
            return baseResp;
        }
        /*将用户名和密码放进map集合中，生成token*/
        Map<String, Object> map = new HashMap<>();
        map.put("username",username);
        map.put("password",password);
        String token = jwtUtils.token(map);

        baseResp.setCode(100000l);
        baseResp.setMessage(token);
        return baseResp;
    }


    @Override
    public BaseResp findClasses(String token) {
        Map map = jwtUtils.Verify(token);

        Object o = JSONObject.toJSON(map);

        TbUser tbUser = JSONObject.parseObject(o.toString(), TbUser.class);
        Integer id = tbUser.getId();

        List<Clsses> classByUserId = classesClient.findClassByUserId(id);

        BaseResp baseResp = new BaseResp();
        baseResp.setCode(200l);
        baseResp.setMessage(classByUserId);
        return baseResp;
    }

}
